package com.health.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.health.domain.pojo.Checkgroup;
import com.health.domain.query.PageQueryDTO;
import com.health.domain.vo.PageBean;
import com.health.domain.vo.Result;
import com.health.mapper.CheckgroupCheckitemMapper;
import com.health.mapper.CheckgroupMapper;
import com.health.service.CheckgroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author ghy
 * @version 1.0
 * @since 2025-06-22 08:10
 */
@Service
public class CheckgroupServiceImpl implements CheckgroupService {

    @Autowired
    private CheckgroupMapper checkgroupMapper;
    @Autowired
    private CheckgroupCheckitemMapper checkgroupCheckitemMapper;

    /**
     * 分页条件查询
     *
     * @param pageQueryDTO 分页参数
     * @return 分页结果
     */
    @Override
    public PageBean<Checkgroup> findPage(PageQueryDTO pageQueryDTO) {
        // 1.设置分页参数
        Integer currentPage = pageQueryDTO.getCurrentPage();
        Integer pageSize = pageQueryDTO.getPageSize();
        String queryString = pageQueryDTO.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        // 2.执行查询
        List<Checkgroup> checkgroupList = checkgroupMapper.selectList(queryString);
        // 3.封装数据
        PageInfo<Checkgroup> pageInfo = new PageInfo<>(checkgroupList);
        return new PageBean<>(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public Result<List<Checkgroup>> findAll() {
        List<Checkgroup> checkgroupList = checkgroupMapper.selectList(null);
        return Result.success(checkgroupList);
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @Override
    public Result<Checkgroup> findById(Integer id) {
        Checkgroup checkgroup = checkgroupMapper.selectById(id);
        return Result.success(checkgroup);
    }

    @Override
    public Result<List<Integer>> findCheckItemIdsByCheckGroupId(Integer id) {
        List<Integer> checkitemIdList = checkgroupCheckitemMapper.selectCheckitemIdsByCheckgroupId(id);
        return Result.success(checkitemIdList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> edit(Integer[] checkitemIds, Checkgroup checkgroup) {
        // 更新检查组信息
        checkgroupMapper.updateById(checkgroup);
        // 删除检查组关联的检查项信息
        checkgroupCheckitemMapper.deleteByCheckgroupId(checkgroup.getId());
        // 新增检查组与检查项的关联信息
        checkgroupCheckitemMapper.insertBatch(checkitemIds, checkgroup.getId());
        return Result.success("修改检查组成功", null);
    }


}
